import http from '@ohos.net.http';
import usb from '@ohos.usb';

function STR(str:string){

  //得到数据
  var l1=str.split("\"body\":\"")
  var ty=l1[1].split("\"")
 // console.info('headerB:'+ty[0] );

  var data_p=ty[0].split("255");

 // data_p.forEach(el =>console.info(el.length+"header0:"+el))
  var final_data=data_p[0].split("a");
  for (let i = 1; i < data_p.length; i++) {
    if(data_p[i].split("a").length>final_data.length){
      final_data=data_p[i].split("a")
    }
  }
  if(final_data.length>=75) {
    console.info('headerB:' + final_data.length + "#" + final_data);
    console.info('header心率:' + final_data.length + "#" + (final_data[64]));
    console.info('header血氧:' + final_data.length + "#" + final_data[65]);
    console.info('header微循环:' + final_data.length + "#" + final_data[66]);
    console.info('header疲劳指数：:' + final_data.length + "#" + final_data[67]);
    console.info('header收缩压：:' + final_data.length + "#" + final_data[70]);
    console.info('header舒张压：:' + final_data.length + "#" + final_data[73]);
    console.info('header心输出：:' + final_data.length + "#" + final_data[74]);
    console.info('header外周阻力：:' + final_data.length + "#" + final_data[75]);
    console.info("--------------------------");
  }

}



export function requestUrl(url:string,callback:(result)=>void){

  let httpRequest = http.createHttp();
  let requestOptions = {
    method:http.RequestMethod.GET,
    connectTimeout:30000,
    readTimeout:30000,
  }

  httpRequest.on('headersReceive',(header)=>{
    //console.info('header:'+JSON.stringify(header));
  });

  let res =httpRequest.request(url,requestOptions)
  res.then((data)=>{

    console.info('header:'+data.result.toString());//.substring(0,50)
    //STR(data.result.toString())


    callback(data.result)
  }).catch((err)=>{
    console.info('header err:'+err);
    httpRequest.destroy();
  })


}



//获得历史数据
export function requestUrlLSData(url:string,callback:(result)=>void){

  let httpRequest = http.createHttp();
  let requestOptions = {
    method:http.RequestMethod.GET,

    connectTimeout:30000,
    readTimeout:30000,
  }

  httpRequest.on('headersReceive',(header)=>{
    //console.info('header:'+JSON.stringify(header));
  });

  let res =httpRequest.request(url,requestOptions)
  res.then((data)=>{

    console.info('header:'+data.result.toString());//.substring(0,50)
    //STR(data.result.toString())


    callback(data.result)
  }).catch((err)=>{
    console.info('header err:'+err);
    httpRequest.destroy();
  })


}



//获得模型评估结果
export function requestUrlBody(url:string,callback:(result)=>void){

  let httpRequest = http.createHttp();
  let requestOptions = {
    method:http.RequestMethod.GET,

    connectTimeout:30000,
    readTimeout:30000,
  }

  httpRequest.on('headersReceive',(header)=>{
    //console.info('header:'+JSON.stringify(header));
  });

  let res =httpRequest.request(url,requestOptions)
  res.then((data)=>{

    console.info('header:'+data.result.toString());//.substring(0,50)
    //STR(data.result.toString())


    callback(data.result)
  }).catch((err)=>{
    console.info('header err:'+err);
    httpRequest.destroy();
  })


}


//获取token
export function requestToken(url:string,callback:(result)=>void){

  let json_data=JSON.stringify('{"auth": {"identity": { "methods": ["password"  ],  "password": { "user": {   "name": "pysuser",  "password": "huawei987654321",  "domain": {  "name": "hid_qoa0xnlwq9o0u8b"  }   }  }  }, "scope": { "project": {   "name": "cn-north-4"  }   } } }')
  let json2={
    auth: {
      identity: {
        methods: "password",
        password: {
          user: {
            name: "pysuser",
            password: "huawei987654321",
            domain: {
              name: "hid_qoa0xnlwq9o0u8b"
            }
          }
        }
      },
      scope: {
        project: {
          name: "cn-north-4"
        }
      }
    }
  }
  console.info('header_json:'+JSON.stringify(json2));

  let httpRequest = http.createHttp();
  let requestOptions = {
    method:http.RequestMethod.POST,
    header:{
      'Content-Type':'application/json;charset=UTF-8'
       },
     extraData:{
       'body':JSON.stringify(json2)
     },




    connectTimeout:30000,
    readTimeout:30000,
  }

  httpRequest.on('headersReceive',(header)=>{
    console.info('header:'+JSON.stringify(header));
  });

  let res =httpRequest.request(url,requestOptions)
  res.then((data)=>{
    console.info('header-1:'+data.result.toString());//.substring(0,50)
    console.info('header0:'+data.responseCode.toString());
    console.info('header1:'+data.header.toString());
    console.info('header2:'+JSON.stringify(data.header));



    let deviceList = usb.getDevices();
    let deviceName = deviceList[0].name;
    console.info('headerUSBList:'+deviceList);
    console.info('headerUSB:'+deviceName);

    // 申请操作指定的device的操作权限。
    usb.requestRight(deviceName).then(hasRight => {
      console.info("usb device request right result: " + hasRight);
    }).catch(error => {
      console.info("usb device request right failed : " + error);
    });

    // 打开设备，获取数据传输通道。
    let pipe = usb.connectDevice(deviceList[0]);
    let interface1 = deviceList[0].configs[0].interfaces[0];
    /*
     打开对应接口，在设备信息（deviceList）中选取对应的interface。
    interface1为设备配置中的一个接口。
    */
    usb.claimInterface(pipe , interface1, true);

    /*
 读取数据，在device信息中选取对应数据接收的endpoint来做数据传输
（endpoint.direction == 0x80）；dataUint8Array是要读取的数据，类型为Uint8Array。
*/
    let inEndpoint = interface1.endpoints[2];
    let outEndpoint = interface1.endpoints[1];
    outEndpoint.direction==0x8A
    let dataUint8Array = new Uint8Array(1024);
    usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => {
      if (dataLength >= 0) {
        console.info("usb readData result Length : " + dataLength);
        let resultStr = this.ab2str(dataUint8Array); // uint8数据转string。
        console.info("usb readData buffer : " + resultStr);
      } else {
        console.info("usb readData failed : " + dataLength);
      }
    }).catch(error => {
      console.info("usb readData error : " + JSON.stringify(error));
    });
    // 发送数据，在device信息中选取对应数据发送的endpoint来做数据传输。（endpoint.direction == 0）
    usb.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then(dataLength => {
      if (dataLength >= 0) {
        console.info("usb writeData result write length : " + dataLength);
      } else {
        console.info("writeData failed");
      }
    }).catch(error => {
      console.info("usb writeData error : " + JSON.stringify(error));
    });


    callback(data.result)
  }).catch((err)=>{
    console.info('header err:'+err);
    httpRequest.destroy();
  })


}